/**
 * 
 */
var FTUserRoutesLayers;
var idActiveRoute=0;

$(window).load(function (){
	initialize();
});

function initialize() {
	//Get the user location via W3C standard
    var initialLocation =new google.maps.LatLng(42.846406,-2.667893);
	//Create the map
	createMap(initialLocation,"auto");
	
	setBlueStyle();
	
	createFTLayers();
	initialLocation=locateUser();
}

function createFTLayers(){
	
	
	FTUserRoutesLayers=new Array();
	for(var i =0; i<routes.length; i++){
		FTUserRouteLayer = new google.maps.FusionTablesLayer(323755,{
			query: "SELECT route FROM 323755 WHERE id="+routes[i]
		});
		FTUserRouteLayer.setMap(map);
		google.maps.event.addListener(FTUserRouteLayer, 'click', tableClicked);
		
		FTUserRoutesLayers[i]=FTUserRouteLayer;
	}	
}

function tableClicked(table) {
	// Funcion que salta cuando se clicka en una ruta de alguna FTLayer
	

	
	if(idActiveRoute!=0){
		$("#foundRoute"+idActiveRoute).css("background-color", "#ffffff");
	}
	idActiveRoute=table.row['id'].value;
	var divRuta=$("#foundRoute"+idActiveRoute);
	divRuta.css("background-color", "#e8e8e8");
	
	var sliderPos=$("#rutas_slider").slider( "option", "value");
	var divRutaPos=divRuta.position().top+sliderPos;
	
	//TODO: Mejorar este metodo, imperfecto cuando se medio-corta una ruta
	if(divRutaPos<0){
		$('#foundRoutes').css("top",  -divRutaPos-divRuta.height() + "px");
		$("#rutas_slider").slider( "option", "value",divRutaPos-sliderPos);
	}
	else{
		var offset=(divRutaPos+divRuta.height())-$('#contentViewer').height();
		if(offset>0){
			$('#foundRoutes').css("top",  -offset + "px");
			$("#rutas_slider").slider( "option", "value",-offset );
		}
	}
}